import { HttpServiceResponse, Service } from '../core';
import { AccountInfo } from './AccountInfo';

export interface Account {
	type?: number;
	principal: string;
	credential: string;
	rememberMe?: boolean;
}

class AccountService extends Service {
	protected create(): AccountService {
		return this.initTokenInstance('account') as AccountService;
	}

	login = (account: Account): Promise<HttpServiceResponse<AccountInfo>> =>
		this.request({
			method: this.method.POST,
			url: '/login',
			data: account,
		});

	logout = (): Promise<HttpServiceResponse<void>> =>
		this.request({
			method: this.method.DELETE,
			url: '/logout',
		});

	information = (): Promise<HttpServiceResponse<AccountInfo>> =>
		this.request({
			method: this.method.GET,
			url: '/information',
		});

	upgradeInfo = (): Promise<HttpServiceResponse<AccountInfo>> =>
		this.request({
			method: this.method.PUT,
			url: '/authorization',
		});

	upgradePassword = (
		oldPassword: string,
		newPassword: string
	): Promise<HttpServiceResponse<void>> =>
		this.request({
			method: this.method.PUT,
			url: '/password',
			data: {
				oldPassword,
				newPassword,
			},
		});

	upgradePhone = (
		password: string,
		newPhone: string
	): Promise<HttpServiceResponse<void>> =>
		this.request({
			method: this.method.PUT,
			url: '/phone',
			data: {
				password,
				newPhone,
			},
		});

	deletePhone = (): Promise<HttpServiceResponse<void>> =>
		this.request({
			method: this.method.DELETE,
			url: '/phone',
		});

	upgradeEmail = (
		password: string,
		newEmail: string
	): Promise<HttpServiceResponse<void>> =>
		this.request({
			method: this.method.PUT,
			url: '/email',
			data: {
				password,
				newEmail,
			},
		});

	deleteEmail = (): Promise<HttpServiceResponse<void>> =>
		this.request({
			method: this.method.DELETE,
			url: '/email',
		});

	upgradeAvatar = (avatar: File): Promise<HttpServiceResponse<void>> => {
		const formData = new FormData();
		formData.append('avatar', avatar);
		return this.request({
			headers: {
				'Content-Type': 'multipart/form-data',
			},
			method: this.method.PUT,
			url: '/avatar',
			data: formData,
		});
	};
}

export const accountService = new AccountService();
